package org.jetnuke.dao.generic;

import org.apache.log4j.Logger;

import java.sql.PreparedStatement;
import java.sql.ResultSet;

import net.jforum.JForumExecutionContext;
import net.jforum.util.preferences.SystemGlobals;

import org.jetnuke.dao.PictureSettingsDAO;
import org.jetnuke.entities.PictureSettings;

public class GenericPictureSettingsDAO implements PictureSettingsDAO {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger
			.getLogger(GenericPictureSettingsDAO.class);

	public PictureSettings get() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("get() - start"); //$NON-NLS-1$
		}

		PreparedStatement p = JForumExecutionContext.getConnection()
				.prepareStatement(
						SystemGlobals.getSql("PictureSettingsModel.get"));

		ResultSet rs = p.executeQuery();
		PictureSettings s = new PictureSettings();

		rs.next();
		fillPictureSettingsFromResultSet(s, rs);

		rs.close();
		p.close();

		if (logger.isDebugEnabled()) {
			logger.debug("get() - end"); //$NON-NLS-1$
		}
		return s;
	}

	private void fillPictureSettingsFromResultSet(PictureSettings s,
			ResultSet rs) throws Exception {
		if (logger.isDebugEnabled()) {
			logger
					.debug("fillPictureSettingsFromResultSet(PictureSettings, ResultSet) - start"); //$NON-NLS-1$
		}

		s.setLICENSE(rs.getString("PICTURE_LICENSE_ACCEPT"));
		s.setLIMIT(rs.getInt("SIZE_LIMIT_KB"));

		if (logger.isDebugEnabled()) {
			logger
					.debug("fillPictureSettingsFromResultSet(PictureSettings, ResultSet) - end"); //$NON-NLS-1$
		}
	}

	public void update(PictureSettings bs) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("update(PictureSettings) - start"); //$NON-NLS-1$
		}

		PreparedStatement p = JForumExecutionContext.getConnection()
				.prepareStatement(
						SystemGlobals.getSql("PictureSettingsModel.update"));
		p.setString(1, bs.getLICENSE());
		p.setInt(2, bs.getLIMIT());
		p.executeUpdate();
		p.close();

		if (logger.isDebugEnabled()) {
			logger.debug("update(PictureSettings) - end"); //$NON-NLS-1$
		}
	}

}
